package com.fishbone.file.fast;

import com.fishbone.file.config.FastProperties;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * @ClassName FastDFSClient
 * @Description fastdfs文件上传工具类
 * @Author 胡亚曦
 * @DATE 2018/11/13 13:41
 */

public class FastDFSClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(FastDFSClient.class);
    private FastProperties properties;
    private StorageClient1 storageClient;

    public FastDFSClient(FastProperties properties) {
        this.properties = properties;
        this.storageClient = createStorage();
    }

    private StorageClient1 createStorage() {
        InetSocketAddress[] trackerServers = {new InetSocketAddress(properties.getHost(), properties.getPort())};
        ClientGlobal.setG_tracker_group(new TrackerGroup(trackerServers));
        TrackerClient trackerClient = new TrackerClient();
        try {
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
            return new StorageClient1(trackerServer, storageServer);
        }catch (Exception ex){
            LOGGER.info("error is:{}",ex);
        }
        return null;
    }

    /**
     * 文件上传
     * @param fileBuff
     * @param extName
     * @param metas
     * @return
     */
    public String uploadFile(byte[] fileBuff, String extName, NameValuePair[] metas){
        try {
            return storageClient.upload_file1(fileBuff, extName, metas);
        }catch (Exception ex){
            LOGGER.info("error is:{}",ex);
        }
        return null;
    }

    /**
     * 文件上传
     * @param fileBuff
     * @param extName
     * @return
     */
    public String uploadFile(byte[] fileBuff, String extName){
        return uploadFile(fileBuff,extName,null);
    }
}
